#!/usr/bin/env python
# -*- coding: cp1252 -*-
from mechanize import Browser
from BeautifulSoup import BeautifulSoup

import re
import msvcrt
import Modules.Inventory
import Modules.Util

mech = Browser()
mech.set_handle_robots(False)
mech.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

mech.open("http://www.bricklink.com/search.asp?viewFrom=sa&shipCountryID=BR&invNew=N&q=3004&searchSort=P&sz=25")

inventory = Modules.Inventory.Inventory("..\Inventory\Katana with Saya.csv")

totalprice = 0
totalbricks = 0
found = 0

for item in inventory.Items[:]:
    url = "http://www.bricklink.com/search.asp?viewFrom=sa&qMin=" + str(item.Quantity) + "&shipCountryID=BR&invNew=N&colorID=" + str(item.ColorNumber) + "&q=" + item.Code + "&searchSort=P&sz=25"
    page = mech.open(url)
    html = page.read()
    soup = BeautifulSoup(html)

    keytext = soup.find(text=re.compile("Available&nbsp;In"))
    if keytext is None:
        print "%s\t%s\t%s\tNao encontrado" % (item.Code, item.Quantity, item.ColorNumber)
        continue

    tr = keytext.parent.findPrevious("tr").findNextSibling()
    td = tr.findAll("td")[3]
    links = td.findAll("a")

    store = links[1].string
    rating = links[2].string
    qty = td.find(text=re.compile("Qty:")).findNextSibling().string
    price = td.find(text=re.compile("Each:")).findNextSibling().string

    totalprice += float(price.replace("BRL", "")) * min(item.Quantity, int(qty.replace(",", "")))
    totalbricks += min(item.Quantity, int(qty.replace(",", "")))

    print "%s\t%s\t%s\t%-30s%-10s%s" % (item.Code, item.Quantity, item.ColorNumber, store.encode('ascii', 'replace') + " " + rating, qty, price)

    found += 1

print "Preco: %f Itens: %d/%d Bricks: %d/%d" % (totalprice, found, len(inventory.Items), totalbricks, inventory.bricksQty())
print "Pressione uma tecla para sair..."
msvcrt.getch()
